/**
 * 
 */
package com.vote.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vote.dao.AnswerInfoDao;
import com.vote.dao.PrizeInfoDao;
import com.vote.dao.PrizeRecordDao;
import com.vote.dao.PrizeSettingDao;
import com.vote.dao.RespondentDao;
import com.vote.entity.PrizeInfo;
import com.vote.entity.PrizeRecord;
import com.vote.entity.PrizeSetting;
import com.vote.entity.Respondent;
import com.vote.util.LotteryUtil;
import com.vote.util.VoteConstants;

//Spring Bean的标识.
@Service
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class PrizeSettingManager{
	
	private static Logger log = LoggerFactory.getLogger(PrizeSettingManager.class);
	
	public final static String RETURNCODE = "returncode";
	public final static String PRIZELEVEL = "prizelevel";
	public final static String PRIZESTYPE="prizetype";
	public final static String PRIZEREMARK = "remark";
	public final static String ISPRIZE = "isprize";
		
	@Autowired
	private PrizeSettingDao prizeSettingDao;
	@Autowired
	private PrizeInfoDao prizeInfoDao;
	
	@Autowired
	private AnswerInfoDao answerInfoDao;
	
	@Autowired	
	private PrizeRecordDao prizeRecordDao;	
	@Autowired	
	private RespondentDao respondentDao;
		
	/**
	 * 开始抽奖
	 * @param ip
	 * @param cookie
	 * @return
	 */
	public Map<String,String> startLottery(String ip,String cookie){
		
		Map<String, String> map = new HashMap<String, String>();
		try {		
			Date now=new Date();
			if(StringUtils.isEmpty(ip) || StringUtils.isEmpty(cookie)){
				map.put(RETURNCODE, "9999");//未答题,没有抽奖资格			
				return map;
			}
			//判断用户
			Respondent resp=respondentDao.findRespondentByIpOrCookie(ip,cookie);		
			if(resp==null){
				map.put(RETURNCODE, "9999");//未答卷,没有抽奖资格			
				return map;
			}	
			//没有答题记录，不能抽奖
			if(answerInfoDao.getAnswerInfoCnt(ip, cookie)<=0){
				map.put(RETURNCODE, "9999");			
				return map;
			}
			//已经抽过奖，不能再中
			if(prizeRecordDao.getPrizeRecordCnt(ip, cookie)>0){
				map.put(RETURNCODE, "9998");		
				return map;
			}			
			//根据该ip查绑定奖
			PrizeInfo prizeInfo=prizeInfoDao.bindIpPrize(ip);	
			//log.info("1");
			//无绑定ip的记录
			if(prizeInfo==null){
				//log.info("2");
				//得到各奖品中奖概率						
				Map<String,Integer> roateMap=this.getPrizeRoate();				
				//log.info("3");
				//计算中奖级别
				Integer prizeLevel=LotteryUtil.getPrize(roateMap);				
				//为0时取最小奖品
				if(prizeLevel.equals(new Integer(0))){
					PrizeSetting minPs=prizeSettingDao.getMinPrizeSetting();
					//log.info("4");
					map.put(RETURNCODE, "0000");
					map.put(PRIZELEVEL,minPs.getPrizeLevel().toString());
					map.put(ISPRIZE,minPs.getIsPrize().toString());					
					log.info("prize prizeLevel:" + prizeLevel + " thx!");
					
					//保存抽奖记录
					PrizeRecord pr=new PrizeRecord();
					pr.setIp(ip);
					pr.setCookie(cookie);
					pr.setPrizeLevel(minPs.getPrizeLevel());
					pr.setPrizeName(minPs.getPrizeName());
					pr.setPrizeSetting(minPs);		
					pr.setRespondent(resp);
					pr.setPrizeInfo(prizeInfo);
					pr.setStatus(VoteConstants.COMMON_STATUS_ENABLE);
					pr.setCreateTime(now);
					pr.setUpdateTime(now);
					prizeRecordDao.save(pr);
					
					return map;
				}else{
					//log.info("5");
					//可中奖奖品
					prizeInfo=prizeInfoDao.getPrizeInfoByLevel(new Long(prizeLevel));					
					//此类奖品已中完，取最小奖品
					if(prizeInfo==null){
						PrizeSetting minPs=prizeSettingDao.getMinPrizeSetting();
						map.put(RETURNCODE, "0000");
						map.put(PRIZELEVEL,minPs.getPrizeLevel().toString());
						map.put(ISPRIZE,minPs.getIsPrize().toString());
						log.info("prize prizeLevel:" + prizeLevel + " win out!");
												
						//保存抽奖记录
						PrizeRecord pr=new PrizeRecord();
						pr.setIp(ip);
						pr.setCookie(cookie);
						pr.setPrizeLevel(minPs.getPrizeLevel());
						pr.setPrizeName(minPs.getPrizeName());
						pr.setPrizeSetting(minPs);		
						pr.setRespondent(resp);
						pr.setPrizeInfo(prizeInfo);
						pr.setStatus(VoteConstants.COMMON_STATUS_ENABLE);
						pr.setCreateTime(now);
						pr.setUpdateTime(now);
						prizeRecordDao.save(pr);
						return map;
					}
				}
			}else{
				log.info("ip:" + ip + " cookie:" + cookie + " bindPrizeName:"+prizeInfo.getPrizeSetting().getPrizeName());
			}			
			//log.info("6");			
			PrizeSetting prizeSetting=prizeSettingDao.get(prizeInfo.getPrizeSetting().getId());			
			prizeInfo.setStatus(VoteConstants.PRIZE_STATUS_USED);
			prizeInfo.setIp(ip);
			prizeInfo.setCookie(cookie);
			prizeInfo.setUpdateTime(now);
			log.info("ip:" + ip + " cookie:" + cookie + " get prizeInfoId:"+prizeInfo.getId());	
			
			PrizeRecord pr=new PrizeRecord();
			pr.setIp(ip);
			pr.setCookie(cookie);
			pr.setPrizeLevel(prizeSetting.getPrizeLevel());
			pr.setPrizeName(prizeSetting.getPrizeName());
			pr.setPrizeSetting(prizeSetting);
			pr.setRespondent(resp);
			pr.setPrizeInfo(prizeInfo);
			pr.setStatus(VoteConstants.COMMON_STATUS_ENABLE);
			pr.setCreateTime(now);
			pr.setUpdateTime(now);
			prizeRecordDao.save(pr);			
			log.info("ip:" + ip + " cookie:" + cookie + " save PrizeRecord id:"+pr.getId());
			
			//是真实奖品更新中奖数量
			if(VoteConstants.PRIZE_SETTING_ISPRIZE_TRUE.equals(prizeSetting.getIsPrize())){
				Long oldNum=prizeSetting.getWinNum()==null?0:prizeSetting.getWinNum();			
				prizeSetting.setWinNum(prizeSetting.getWinNum()==null?1:prizeSetting.getWinNum()+1);
				prizeSetting.setUpdateTime(now);
				prizeSettingDao.update(prizeSetting);
				log.info("ip:" + ip + " cookie:" + cookie + " update num :"+oldNum+" to "+prizeSetting.getWinNum());
			}		
			map.put(RETURNCODE, "0000");
			map.put(PRIZELEVEL,prizeSetting.getPrizeLevel().toString());
			map.put(PRIZESTYPE,prizeSetting.getPrizeType().toString());
			map.put(ISPRIZE,prizeSetting.getIsPrize().toString());			
			map.put(PRIZEREMARK, prizeSetting.getPrizeName());
		} catch (Exception e) {
			e.printStackTrace();
			PrizeSetting minPs=prizeSettingDao.getMinPrizeSetting();
			map.put(RETURNCODE, "0000");
			map.put(PRIZELEVEL,minPs.getPrizeLevel().toString());
			map.put(ISPRIZE,minPs.getIsPrize().toString());
			return map;
		}
		return map;				
	}
	
	public Map<String,Integer> getPrizeRoate(){
		Map<String,Integer> roateMap=null;
		List<PrizeSetting> psLst=prizeSettingDao.listPrizeSettings();	
		if(psLst!=null && !psLst.isEmpty()){
			roateMap=new HashMap<String,Integer>();
			log.info("PrizeSetting size:"+psLst.size());
			for(PrizeSetting ps:psLst){
				roateMap.put(ps.getPrizeLevel().toString(), ps.getPrizeRate().intValue());
			}
		}		
		return roateMap;
	}
	public PrizeSettingDao getPrizeSettingDao() {
		return prizeSettingDao;
	}
	public void setPrizeSettingDao(PrizeSettingDao prizeSettingDao) {
		this.prizeSettingDao = prizeSettingDao;
	}	
}
